<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Db;
// 应用公共文件
/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}
function adminLog($log_info)
{
    $add['log_time'] = time();
    $add['admin_id'] = session('admin_id');
    $add['log_info'] = $log_info;
    $add['log_ip'] = request()->ip();
    $add['log_url'] = request()->baseUrl();
    Db('admin_log')->insert($add);
}

function encrypt($pwd, $salt) {
    $pwd = md5(md5($pwd) . $salt);
    return $pwd;
}

/**
 * @param $en_pwd 已加密密码
 * @param $password 未加密密码
 * @param $salt
 */
function password_compare($en_pwd, $password, $salt) {
    $newpwd = md5(md5($password) . $salt);

    if ($en_pwd == $newpwd) {
        return true;
    }
    return false;
}

function getMenuArr(){
    $menuArr = include APP_PATH . 'admin/conf/menu.php';
    $act_list = session('act_list');
    if($act_list != 'all' && !empty($act_list)){
        $right = Db('system_menu')->where("id in ($act_list)")->cache(true)->column('right');
        $role_right = '';
        foreach ($right as $val){
            $role_right .= $val.',';
        }
        foreach($menuArr as $k=>$val){
            foreach ($val['child'] as $j=>$v){
//                foreach ($v['child'] as $s=>$son){
//                    if(strpos($role_right,$son['op'].'@'.$son['act']) === false){
//                        unset($menuArr[$k]['child'][$j]['child'][$s]);//过滤菜单
//                    }
//                }

                if(strpos($role_right,$v['op'].'@'.$v['act']) === false){
                    unset($menuArr[$k]['child'][$j]);//过滤菜单
                }

            }
        }
        foreach ($menuArr as $mk=>$mr){

            if (empty($mr['child'])) {
                unset($menuArr[$mk]['child']);
            }

//            foreach ($mr['child'] as $nk=>$nrr){
//                if(empty($nrr['child'])){
//                    unset($menuArr[$mk]['child'][$nk]);
//                }
//            }
        }
    }
    return $menuArr;
}

/**
 * 操作按钮
 * @param $array
 * @return string
 */
function actionList($array) {
    if (empty($array)) {
        return '';
    }
    if (!is_array($array)) {
        return $array;
    }
    $str = '';
    foreach ($array as $v) {
        if ($v['type'] == 'add') {
            $class = "am-btn am-btn-default am-btn-success";
            $i_class = "am-icon-plus";
        }else if ($v['type'] == 'delete'){
            $class = "am-btn am-btn-default am-btn-danger js-ajax-submit";
            $i_class = "am-icon-trash-o";
        }else if($v['type'] == 'check') {
            //审核
            $class = "am-btn am-btn-default am-btn-warning js-ajax-submit";
            $i_class = "am-icon-archive";
        }else if ($v['type'] == 'order') {
            //排序
            $class = "am-btn am-btn-default am-btn-warning js-ajax-submit";
            $i_class = "am-icon-archive";
        }
        $popover = '';
        if (isset($v['data-am-popover'])) {
            $popover = 'data-am-popover="'.$v['data-am-popover'].'"';
        }
        $href = $v['button'] == 'button' ? " type='submit' data-action='{$v['href']}'" : " href='{$v['href']}'";
        $str .= "<".$v['button']. $href. " class='".$class. "' data-subcheck='true' data-msg='".$v['msg']."' $popover>";
        $str .= "<i class='".$i_class."'>".$v['text']."</i>";
        $str .= "</".$v['button'].">";
    }
    return $str;

}

/**
 *
 * 中英混合字符串长度判断
 * @param unknown_type $str
 * @param unknown_type $charset
 */
function strLength($str, $charset = 'utf-8') {
    if ($charset == 'utf-8')
        $str = iconv ( 'utf-8', 'gb2312', $str );
    $num = strlen ( $str );
    $cnNum = 0;
    for($i = 0; $i < $num; $i ++) {
        if (ord ( substr ( $str, $i + 1, 1 ) ) > 127) {
            $cnNum ++;
            $i ++;
        }
    }
    $enNum = $num - ($cnNum * 2);
    $number = ($enNum / 2) + $cnNum;
    return ceil ( $number );
}
/**
 *
 * 中英混合的字符串截取
 * @param unknown_type $sourcestr
 * @param unknown_type $cutlength
 */
function cut_str($sourcestr, $cutlength) {
    $returnstr = '';
    $i = 0;
    $n = 0;
    $str_length = strlen ( $sourcestr ); //字符串的字节数
    while ( ($n < $cutlength) and ($i <= $str_length) ) {
        $temp_str = substr ( $sourcestr, $i, 1 );
        $ascnum = Ord ( $temp_str ); //得到字符串中第$i位字符的ascii码
        if ($ascnum >= 224) //如果ASCII位高与224，
        {
            $returnstr = $returnstr . substr ( $sourcestr, $i, 3 ); //根据UTF-8编码规范，将3个连续的字符计为单个字符
            $i = $i + 3; //实际Byte计为3
            $n ++; //字串长度计1
        } elseif ($ascnum >= 192) //如果ASCII位高与192，
        {
            $returnstr = $returnstr . substr ( $sourcestr, $i, 2 ); //根据UTF-8编码规范，将2个连续的字符计为单个字符
            $i = $i + 2; //实际Byte计为2
            $n ++; //字串长度计1
        } elseif ($ascnum >= 65 && $ascnum <= 90) //如果是大写字母，
        {
            $returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
            $i = $i + 1; //实际的Byte数仍计1个
            $n ++; //但考虑整体美观，大写字母计成一个高位字符
        } else //其他情况下，包括小写字母和半角标点符号，
        {
            $returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
            $i = $i + 1; //实际的Byte数计1个
            $n = $n + 0.5; //小写字母和半角标点等与半个高位字符宽...
        }
    }
    if ($str_length > $cutlength) {
        $returnstr = $returnstr . "..."; //超过长度时在尾处加上省略号
    }
    return $returnstr;
}

/* PHP截取utf-8中文字符串
* @param $str 被截取的字符串
* @param $start 起始长度
* @param $len 截取长度
* @param $suffix 后缀字符串
*/
function utf8_str($str,$start,$len,$suffix=""){
    $tmpstr = "";
    $n = 0;
    $i = 0;
    $length = $start+$len;
    while($i<strlen($str)){
        $value = ord($str[$i]);
        if($value >= 65 && $value <= 90){//大写字母
            if($n>=$start && $n<$length){
                $tmpstr .= substr($str,$i,1);
            }
            $n++;
            $i++;
        }
        elseif($value >= 192 && $value <= 223){
            if($n>=$start && $n<$length){
                $tmpstr .= substr($str,$i,2);
            }
            $n++;
            $i+=2;
        }
        elseif($value >= 224 && $value <= 239){
            if($n>=$start && $n<$length){
                $tmpstr .= substr($str,$i,3);
            }
            $n++;
            $i+=3;
        }
        elseif($value >= 240 && $value <= 247){
            if($n>=$start && $n<$length){
                $tmpstr .= substr($str,$i,4);
            }
            $n++;
            $i+=4;
        }
        else{//其他情况下，包括小写字母和半角标点符号
            if($n>=$start && $n<$length){
                $tmpstr .= substr($str,$i,1);
            }
            $n += 0.5;
            $i++;
        }
    }
    if($n<$len){
        return $tmpstr;
    }else{
        return $tmpstr.$suffix;
    }
}

/**
 * 字符串截取
 * @param $str
 * @param $length
 * @param string $suffix
 */
function str_substr($str, $length, $suffix = '') {
    $substr = substr($str, 0, $length);
    if (strlen($str) > $length) {
        return $substr.$suffix;
    }
    return $substr;
}
function getMenuList($act_list){
    //根据角色权限过滤菜单
    $menu_list = getAllMenu();
    if($act_list != 'all'){
        $right = Db('system_menu')->where("id", "in", $act_list)->cache(true)->column('right');
        $role_right = '';
        foreach ($right as $val){
            $role_right .= $val.',';
        }
        $role_right = explode(',', $role_right);
        foreach($menu_list as $k=>$mrr){
            foreach ($mrr['sub_menu'] as $j=>$v){
                if(!in_array($v['control'].'@'.$v['act'], $role_right)){
                    unset($menu_list[$k]['sub_menu'][$j]);//过滤菜单
                }
            }
        }
    }
    return $menu_list;
}

function getAllMenu(){
    return	array(
        'system' => array('name'=>'系统设置','icon'=>'fa-cog','sub_menu'=>array(
            array('name'=>'网站设置','act'=>'index','control'=>'System'),
            array('name'=>'友情链接','act'=>'linkList','control'=>'Article'),
            array('name'=>'自定义导航','act'=>'navigationList','control'=>'System'),
            array('name'=>'区域管理','act'=>'region','control'=>'Tools'),
            array('name'=>'短信模板','act'=>'index','control'=>'SmsTemplate'),

        )),
        'access' => array('name' => '权限管理', 'icon'=>'fa-gears', 'sub_menu' => array(
            array('name'=>'权限资源列表','act'=>'right_list','control'=>'System'),
            array('name' => '管理员列表', 'act'=>'index', 'control'=>'Admin'),
            array('name' => '角色管理', 'act'=>'role', 'control'=>'Admin'),
            array('name' => '供应商管理', 'act'=>'supplier', 'control'=>'Admin'),
            array('name' => '管理员日志', 'act'=>'log', 'control'=>'Admin'),
        )),
        'member' => array('name'=>'会员管理','icon'=>'fa-user','sub_menu'=>array(
            array('name'=>'会员列表','act'=>'index','control'=>'User'),
            array('name'=>'会员等级','act'=>'levelList','control'=>'User'),
            array('name'=>'充值记录','act'=>'recharge','control'=>'User'),
            array('name' => '提现申请', 'act'=>'withdrawals', 'control'=>'User'),
            array('name' => '汇款记录', 'act'=>'remittance', 'control'=>'User'),
            //array('name'=>'会员整合','act'=>'integrate','control'=>'User'),
        )),
        'goods' => array('name' => '商品管理', 'icon'=>'fa-book', 'sub_menu' => array(
            array('name' => '商品分类', 'act'=>'categoryList', 'control'=>'Goods'),
            array('name' => '商品列表', 'act'=>'goodsList', 'control'=>'Goods'),
            array('name' => '商品模型', 'act'=>'goodsTypeList', 'control'=>'Goods'),
            array('name' => '商品规格', 'act' =>'specList', 'control' => 'Goods'),
            array('name' => '商品属性', 'act'=>'goodsAttributeList', 'control'=>'Goods'),
            array('name' => '品牌列表', 'act'=>'brandList', 'control'=>'Goods'),
            array('name' => '商品评论','act'=>'index','control'=>'Comment'),
            array('name' => '商品咨询','act'=>'ask_list','control'=>'Comment'),
        )),
        'order' => array('name' => '订单管理', 'icon'=>'fa-money', 'sub_menu' => array(
            array('name' => '订单列表', 'act'=>'index', 'control'=>'Order'),
            array('name' => '发货单', 'act'=>'delivery_list', 'control'=>'Order'),
            //array('name' => '快递单', 'act'=>'express_list', 'control'=>'Order'),
            array('name' => '退货单', 'act'=>'return_list', 'control'=>'Order'),
            array('name' => '添加订单', 'act'=>'add_order', 'control'=>'Order'),
            array('name' => '订单日志', 'act'=>'order_log', 'control'=>'Order'),
        )),
        'promotion' => array('name' => '促销管理', 'icon'=>'fa-bell', 'sub_menu' => array(
            array('name' => '抢购管理', 'act'=>'flash_sale', 'control'=>'Promotion'),
            array('name' => '团购管理', 'act'=>'group_buy_list', 'control'=>'Promotion'),
            array('name' => '商品促销', 'act'=>'prom_goods_list', 'control'=>'Promotion'),
            array('name' => '订单促销', 'act'=>'prom_order_list', 'control'=>'Promotion'),
            array('name' => '代金券管理','act'=>'index', 'control'=>'Coupon'),
            array('name' => '预售管理','act'=>'pre_sell_list', 'control'=>'Promotion'),
        )),
        'Ad' => array('name' => '广告管理', 'icon'=>'fa-flag', 'sub_menu' => array(
            array('name' => '广告列表', 'act'=>'adList', 'control'=>'Ad'),
            array('name' => '广告位置', 'act'=>'positionList', 'control'=>'Ad'),
        )),
        'content' => array('name' => '内容管理', 'icon'=>'fa-comments', 'sub_menu' => array(
            array('name' => '文章列表', 'act'=>'articleList', 'control'=>'Article'),
            array('name' => '文章分类', 'act'=>'categoryList', 'control'=>'Article'),
            //array('name' => '帮助管理', 'act'=>'help_list', 'control'=>'Article'),
            //array('name' => '公告管理', 'act'=>'notice_list', 'control'=>'Article'),
            array('name' => '专题列表', 'act'=>'topicList', 'control'=>'Topic'),
        )),
        'weixin' => array('name' => '微信管理', 'icon'=>'fa-weixin', 'sub_menu' => array(
            array('name' => '公众号管理', 'act'=>'index', 'control'=>'Wechat'),
            array('name' => '微信菜单管理', 'act'=>'menu', 'control'=>'Wechat'),
            array('name' => '文本回复', 'act'=>'text', 'control'=>'Wechat'),
            array('name' => '图文回复', 'act'=>'img', 'control'=>'Wechat'),
            //array('name' => '组合回复', 'act'=>'nes', 'control'=>'Wechat'),
            //array('name' => '消息推送', 'act'=>'news', 'control'=>'Wechat'),
        )),
        'theme' => array('name' => '模板管理', 'icon'=>'fa-adjust', 'sub_menu' => array(
            array('name' => 'PC端模板', 'act'=>'templateList?t=pc', 'control'=>'Template'),
            array('name' => '手机端模板', 'act'=>'templateList?t=mobile', 'control'=>'Template'),
        )),

        'distribut' => array('name' => '分销管理', 'icon'=>'fa-cubes', 'sub_menu' => array(
            array('name' => '分销商品列表', 'act'=>'goods_list', 'control'=>'Distribut'),
            array('name' => '分销商列表', 'act'=>'distributor_list', 'control'=>'Distribut'),
            array('name' => '分销关系', 'act'=>'tree', 'control'=>'Distribut'),
            array('name' => '分销设置', 'act'=>'set', 'control'=>'Distribut'),
            array('name' => '分成日志', 'act'=>'rebate_log', 'control'=>'Distribut'),
        )),

        'tools' => array('name' => '插件工具', 'icon'=>'fa-plug', 'sub_menu' => array(
            array('name' => '插件列表', 'act'=>'index', 'control'=>'Plugin'),
            array('name' => '数据备份', 'act'=>'index', 'control'=>'Tools'),
            array('name' => '数据还原', 'act'=>'restore', 'control'=>'Tools'),
        )),
        'count' => array('name' => '统计报表', 'icon'=>'fa-signal', 'sub_menu' => array(
            array('name' => '销售概况', 'act'=>'index', 'control'=>'Report'),
            array('name' => '销售排行', 'act'=>'saleTop', 'control'=>'Report'),
            array('name' => '会员排行', 'act'=>'userTop', 'control'=>'Report'),
            array('name' => '销售明细', 'act'=>'saleList', 'control'=>'Report'),
            array('name' => '会员统计', 'act'=>'user', 'control'=>'Report'),
            array('name' => '财务统计', 'act'=>'finance', 'control'=>'Report'),
        )),
        'pickup' => array('name' => '自提点管理', 'icon'=>'fa-anchor', 'sub_menu' => array(
            array('name' => '自提点列表', 'act'=>'index', 'control'=>'Pickup'),
            array('name' => '添加自提点', 'act'=>'add', 'control'=>'Pickup'),
        ))
    );
}
function getAdminInfo($admin_id){
    return Db('admin_user')->where("admin_id", $admin_id)->find();
}
/**
 * @param $arr
 * @param $key_name
 * @return array
 * 将数据库中查出的列表以指定的 id 作为数组的键名
 */
function convert_arr_key($arr, $key_name)
{
    $arr2 = array();
    foreach($arr as $key => $val){
        $arr2[$val[$key_name]] = $val;
    }
    return $arr2;
}
/**
 * 获取数组中的某一列
 * @param array $arr 数组
 * @param string $key_name  列名
 * @return array  返回那一列的数组
 */
function get_arr_column($arr, $key_name)
{
    $arr2 = array();
    foreach($arr as $key => $val){
        $arr2[] = $val[$key_name];
    }
    return $arr2;
}